<template>
  <div class="container">
    <div class="title" v-if="!editAcceptId">新建{{ editAcceptId }}</div>
    <div class="title" v-else>
      <span>修改</span> <span class="back" @click="back"> <i class="iconfont icon-fanhui"></i> 返回 </span>
    </div>

    <div class="wrap">
      <el-row>
        <el-col :lg="16" :md="20" :sm="24" :xs="24">
          <el-form :model="accept" status-icon ref="form" label-width="100px" @submit.prevent :rules="rules">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="accept.username" placeholder="请填写用户名"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="accept.phone" placeholder="请填写联系电话"></el-input>
            </el-form-item>
            <el-form-item label="终端类型" prop="type">
              <el-input v-model="accept.type" placeholder="请填写终端类型"></el-input>
            </el-form-item>
            <el-form-item label="型号颜色" prop="model">
              <el-input v-model="accept.model" placeholder="请填写型号颜色"></el-input>
            </el-form-item>
            <el-form-item label="维修性质" prop="nature">
              <el-input v-model="accept.nature" placeholder="请填写维修性质"></el-input>
            </el-form-item>
            <el-form-item label="本机号码" prop="local_number">
              <el-input v-model="accept.local_number" placeholder="请填写本机号码"></el-input>
            </el-form-item>
            <el-form-item label="机身号码" prop="serial_no">
              <el-input v-model="accept.serial_no" placeholder="请填写机身号码"></el-input>
            </el-form-item>
            <el-form-item label="附件" prop="file">
              <el-upload
                ref="uploadRef"
                v-model="accept.file"
                class="upload-demo"
                action="http://localhost:5000/cms/file"
                :on-preview="methods.handlePreview"
                :on-remove="methods.handleRemove"
                :on-change="methods.handleChange"
                :before-remove="methods.beforeRemove"
                multiple
                :limit="3"
                :on-exceed="methods.handleExceed"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
              <!--              <el-input v-model="accept.file" placeholder="请填写附件"></el-input>-->
            </el-form-item>
            <el-form-item label="故障现象描述" prop="describe">
              <el-input v-model="accept.describe" placeholder="请填写故障现象描述"></el-input>
            </el-form-item>
            <el-form-item label="取机时间" prop="receive_time">
              <el-date-picker
                style="width: 100%"
                v-model="accept.receive_time"
                type="datetime"
                placeholder="请填写取机时间"
              >
              </el-date-picker>
              <!--                <el-input v-model="accept.receive_time" placeholder="请填写取机时间"></el-input>-->
            </el-form-item>
            <el-form-item label="受理人" prop="accepted_by">
              <el-input v-model="accept.accepted_by" placeholder="请填写受理人"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="accept.remark" placeholder="请填写备注"></el-input>
            </el-form-item>

            <el-form-item class="submit">
              <el-button type="primary" @click="submitForm">保 存</el-button>
              <el-button @click="resetForm">重 置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import acceptModel from '@/model/accept'
import axios from 'axios'
import router from '@/router'

export default {
  props: {
    editAcceptId: {
      type: Number,
      default: null,
    },
  },
  setup(props, context) {
    const uploadRef = ref(null)
    const form = ref(null)
    const fileList = ref([])
    const loading = ref(false)
    const accept = reactive({
      username: '',
      phone: '',
      type: '',
      model: '',
      nature: '',
      local_number: '',
      serial_no: '',
      file: '',
      describe: '',
      receive_time: '',
      accepted_by: '',
      remark: '',
    })

    const methods = {
      handleRemove(file, fileListp) {
        fileList.value = fileListp
        console.log(file, fileListp)
      },
      handleChange(file, fileListp) {
        fileList.value = fileListp
        console.log(file, fileListp)
      },
      handlePreview(file) {
        downloadFile(file.response[0].url, file.name)
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`,
        )
      },
      // beforeRemove(file,fileListp) {
      //   return this.$confirm(`确定移除 ${file.name}？`)
      // }
    }

    const downloadFile = (u, n) => {
      // axios.get(u, { responseType: 'blob' })
      //   .then(res => {
      //     const blob = new Blob([res.data])
      //     const link = document.createElement('a')
      //     link.href = URL.createObjectURL(blob)
      //     link.download =n
      //     link.click()
      //     URL.revokeObjectURL(link.href)
      //   })
      //   .catch(console.error)
      const xml = new XMLHttpRequest()
      xml.open('GET', u, true)
      xml.responseType = 'blob'
      xml.onload = function () {
        const url = window.URL.createObjectURL(xml.response)
        const a = document.createElement('a')
        a.href = url
        a.download = n
        a.click()
      }
      xml.send()
    }

    const listAssign = (a, b) => Object.keys(a).forEach(key => {
      a[key] = b[key] || a[key]
    })

    /**
     * 表单规则验证
     */
    const { rules } = getRules()

    onMounted(() => {
      if (props.editAcceptId) {
        getAccept()
      }
    })

    const getAccept = async () => {
      loading.value = true
      const res = await acceptModel.getAccept(props.editAcceptId)
      listAssign(accept, res)
      // debugger
      fileList.value = JSON.parse(accept.file)
      loading.value = false
    }

    // 重置表单
    const resetForm = () => {
      form.value.resetFields()
      uploadClearFile()
    }

    const uploadClearFile = () => {
      fileList.value = []
      uploadRef.value.clearFiles()
    }

    const submitForm = async formName => {
      console.log(this)
      form.value.validate(async valid => {
        if (valid) {
          let res = {}
          let params = { ...accept }
          if (fileList.value.length > 0) {
            params = { ...accept, ...{ file: JSON.stringify(fileList.value) } }
          }

          if (props.editAcceptId) {
            res = await acceptModel.editAccept(props.editAcceptId, params)
            context.emit('editClose')
          } else {
            res = await acceptModel.createAccept(params)
            resetForm(formName)
            router.push({ path: '/accept/list' })
          }
          if (res.code < window.MAX_SUCCESS_CODE) {
            // this.$refs.upload.clearFiles();
            uploadClearFile()
            ElMessage.success(`${res.message}`)
          }
        } else {
          console.error('error submit!!')
          ElMessage.error('请将信息填写完整')
        }
      })
    }

    const back = () => {
      context.emit('editClose')
    }

    return {
      back,
      accept,
      form,
      rules,
      resetForm,
      submitForm,
      methods,
      fileList,
      uploadRef,
    }
  },
}

/**
 * 表单验证规则
 */
function getRules() {
  /**
   * 验证回调函数
   */
  const checkInfo = (rule, value, callback) => {
    if (!value) {
      callback(new Error('信息不能为空'))
    }
    callback()
  }
  const rules = {
    order_number: [{ validator: checkInfo, trigger: 'blur', required: true }],
    username: [{ validator: checkInfo, trigger: 'blur', required: true }],
    phone: [{ validator: checkInfo, trigger: 'blur', required: true }],
    order_time: [{ validator: checkInfo, trigger: 'blur', required: true }],
    type: [{ validator: checkInfo, trigger: 'blur', required: true }],
    model: [{ validator: checkInfo, trigger: 'blur', required: true }],
    nature: [{ validator: checkInfo, trigger: 'blur', required: true }],
    local_number: [{ validator: checkInfo, trigger: 'blur', required: true }],
    serial_no: [{ validator: checkInfo, trigger: 'blur', required: true }],
    describe: [{ validator: checkInfo, trigger: 'blur', required: true }],
    receive_time: [{ validator: checkInfo, trigger: 'blur', required: true }],
    accepted_by: [{ validator: checkInfo, trigger: 'blur', required: true }],
    remark: [{ validator: checkInfo, trigger: 'blur', required: true }],
  }
  return { rules }
}
</script>

<style lang="scss" scoped>
.container {
  .title {
    height: 59px;
    line-height: 59px;
    color: $parent-title-color;
    font-size: 16px;
    font-weight: 500;
    text-indent: 40px;
    border-bottom: 1px solid #dae1ec;

    .back {
      float: right;
      margin-right: 40px;
      cursor: pointer;
    }
  }

  .wrap {
    padding: 20px;
  }

  .submit {
    float: left;
  }
}
</style>
